package com.huluobo.a2107mvpimdemo.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;

/**
 * 判断当前网络状态工具类
 * Created by LC on 2023/10/8.
 */
public class NetUtils {
    //单例模式核心,私有化构造方法
    private NetUtils() {
    }

    private static NetUtils netUtils = null;

    private static Context mContext;

    public static NetUtils getNetUtils(Context context) {
        if (netUtils == null) {
            netUtils = new NetUtils();
        }
        mContext = context;
        return netUtils;
    }

    //判断当前网络是否连接的方法
    public boolean isConnected() {
        //获取网络连接的管理器
        ConnectivityManager connectivityManager =
                (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        //拿到当前的网络信息
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        //判断当前有网络信息,并且当前网络状态是已连接或者连接中
        return networkInfo != null && networkInfo.isConnectedOrConnecting();
    }

    //判断当前网络速率是否大于100kps
    public boolean isSlowlyNetWork() {
        //获取网络连接的管理器
        ConnectivityManager connectivityManager =
                (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        //网络流量管理器
        NetworkCapabilities networkCapabilities =
                connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());

        //判断当前的网络状态是蜂窝数据,2G 3G 4G
        if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            if (networkCapabilities.getLinkUpstreamBandwidthKbps() > 100
                    && networkCapabilities.getLinkDownstreamBandwidthKbps() > 100) {
                //如果网络上下行速度都大于100kps,证明当前不是弱网状态
                return false;
            } else {
                //慢
                return true;
            }
        }
        return true;
    }
}
